package com.ruoyi.web.controller.system;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.QualificationStudent;
import com.ruoyi.system.service.IQualificationStudentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;

/**
 * 警校考生资格审查信息Controller
 * 
 * @author ruoyi
 * @date 2025-04-01
 */
@RestController
@RequestMapping("/system/qualification")
public class QualificationStudentController extends BaseController
{
    @Autowired
    private IQualificationStudentService qualificationStudentService;

    /**
     * 查询警校考生资格审查信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:qualification:list')")
    @GetMapping("/list")
    public TableDataInfo list(QualificationStudent qualificationStudent)
    {
        startPage();
        List<QualificationStudent> list = qualificationStudentService.selectQualificationStudentList(qualificationStudent);
        return getDataTable(list);
    }

    /**
     * 导出警校考生资格审查信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:qualification:export')")
    @Log(title = "警校考生资格审查信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QualificationStudent qualificationStudent)
    {
        List<QualificationStudent> list = qualificationStudentService.selectQualificationStudentList(qualificationStudent);
        ExcelUtil<QualificationStudent> util = new ExcelUtil<QualificationStudent>(QualificationStudent.class);
        util.exportExcel(response, list, "警校考生资格审查信息数据");
    }

    /**
     * 导入警校考生资格审查信息
     */
    @PreAuthorize("@ss.hasPermi('system:qualification:import')")
    @Log(title = "警校考生资格审查信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<QualificationStudent> util = new ExcelUtil<QualificationStudent>(QualificationStudent.class);
        List<QualificationStudent> qualificationStudentList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = qualificationStudentService.importQualificationStudent(qualificationStudentList, updateSupport, operName);
        return success(message);
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<QualificationStudent> util = new ExcelUtil<QualificationStudent>(QualificationStudent.class);
        List<QualificationStudent> list = new ArrayList<QualificationStudent>();
        
        // 添加50条样例数据
        for (int i = 1; i <= 50; i++) {
            QualificationStudent student = new QualificationStudent();
            student.setRegistrationId("BM" + String.format("%08d", i));
            student.setName("考生" + i);
            student.setIdCard(generateIdCard());
            student.setGender(i % 3 == 0 ? "女" : "男");
            student.setNativeCity(getRandomCity());
            student.setWrittenExamNo("XP" + String.format("%07d", i));
            student.setComputerExamNo("XJ" + String.format("%07d", i));
            student.setAdministrativeScore(new BigDecimal(String.format("%.1f", 60 + Math.random() * 30)));
            student.setEssayScore(new BigDecimal(String.format("%.1f", 60 + Math.random() * 20)));
            student.setProfessionalScore(new BigDecimal(String.format("%.1f", 65 + Math.random() * 25)));
            
            // 计算总成绩和合成分数
            BigDecimal totalScore = student.getAdministrativeScore().add(student.getEssayScore()).add(student.getProfessionalScore());
            student.setTotalScore(totalScore);
            student.setCompositeScore(new BigDecimal(String.format("%.2f", totalScore.doubleValue() * 0.8)));
            
            student.setInterviewScore(new BigDecimal(String.format("%.1f", 70 + Math.random() * 20)));
            student.setAdministrativeAbsent("");
            student.setEssayAbsent("");
            student.setProfessionalAbsent("");
            student.setPoliticalStatus(getRandomPoliticalStatus());
            student.setHighestDegree(getRandomDegree());
            student.setAcademicDegree(student.getHighestDegree().equals("博士研究生") || student.getHighestDegree().equals("硕士研究生") ? 
                                    (student.getHighestDegree().equals("博士研究生") ? "博士" : "硕士") : 
                                    (student.getHighestDegree().equals("本科") ? "学士" : ""));
            student.setGraduateSchool(getRandomSchool());
            student.setDepartment(getRandomDepartment());
            student.setMajor(getRandomMajor(student.getDepartment()));
            student.setPhoneNumber("1" + (3 + new Random().nextInt(7)) + String.format("%09d", new Random().nextInt(1000000000)));
            student.setQualificationReview(getRandomQualificationResult());
            
            list.add(student);
        }
        
        util.exportExcel(response, list, "警校考生资格审查信息");
    }
    
    /**
     * 生成随机身份证号
     */
    private String generateIdCard() {
        // 随机生成区域码(6位)
        String[] areaCodes = {"110101", "310101", "440101", "330101", "320101", "420101", "510101", "130101", "370101", "500101"};
        String areaCode = areaCodes[new Random().nextInt(areaCodes.length)];
        
        // 随机生成出生日期(8位): 1980-01-01到2004-12-31
        Calendar calendar = Calendar.getInstance();
        calendar.set(1980, 0, 1);
        long start = calendar.getTimeInMillis();
        calendar.set(2004, 11, 31);
        long end = calendar.getTimeInMillis();
        
        long random = start + (long) (Math.random() * (end - start));
        calendar.setTimeInMillis(random);
        
        String year = String.valueOf(calendar.get(Calendar.YEAR));
        String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
        String day = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH));
        String birthday = year + month + day;
        
        // 随机生成顺序码(3位)
        String sequenceCode = String.format("%03d", new Random().nextInt(1000));
        
        // 生成校验码
        String base = areaCode + birthday + sequenceCode;
        char[] validateCode = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        
        int sum = 0;
        for (int i = 0; i < base.length(); i++) {
            sum += Character.getNumericValue(base.charAt(i)) * weights[i];
        }
        
        int mod = sum % 11;
        String idCard = base + validateCode[mod];
        
        return idCard;
    }
    
    /**
     * 获取随机城市
     */
    private String getRandomCity() {
        String[] cities = {"北京市", "上海市", "广州市", "深圳市", "杭州市", "南京市", "武汉市", "成都市", "重庆市", "西安市", 
                         "济南市", "青岛市", "苏州市", "郑州市", "长沙市", "福州市", "厦门市", "合肥市", "南昌市", "天津市"};
        return cities[new Random().nextInt(cities.length)];
    }
    
    /**
     * 获取随机政治面貌
     */
    private String getRandomPoliticalStatus() {
        String[] status = {"中共党员", "中共预备党员", "共青团员", "民革党员", "民盟盟员", "民建会员", "民进会员", "农工党党员", "致公党党员", "九三学社社员", "台盟盟员", "无党派人士", "群众"};
        int randomIndex = new Random().nextInt(100);
        if (randomIndex < 15) return status[0]; // 中共党员的概率较高
        if (randomIndex < 25) return status[1]; 
        if (randomIndex < 60) return status[2]; // 共青团员的概率较高
        if (randomIndex < 98) return status[12]; // 群众的概率较高
        return status[3 + new Random().nextInt(status.length - 3)]; // 其他情况
    }
    
    /**
     * 获取随机学历
     */
    private String getRandomDegree() {
        String[] degrees = {"博士研究生", "硕士研究生", "本科", "大专"};
        int randomIndex = new Random().nextInt(100);
        if (randomIndex < 5) return degrees[0]; // 博士的概率较低
        if (randomIndex < 30) return degrees[1]; // 硕士的概率适中
        if (randomIndex < 90) return degrees[2]; // 本科的概率较高
        return degrees[3]; // 大专的概率较低
    }
    
    /**
     * 获取随机学校
     */
    private String getRandomSchool() {
        String[] schools = {"北京大学", "清华大学", "中国人民大学", "复旦大学", "上海交通大学", "浙江大学", "南京大学", "武汉大学", 
                         "中山大学", "华中科技大学", "四川大学", "南开大学", "东南大学", "中国科学技术大学", "西安交通大学", 
                         "中央财经大学", "中国政法大学", "北京师范大学", "同济大学", "华南理工大学", "北京理工大学", "哈尔滨工业大学", 
                         "中国社会科学院大学", "中国公安大学", "中国刑事警察学院", "公安海警学院"};
        
        Random random = new Random();
        if (random.nextInt(100) < 15) {
            // 返回警校相关学校的概率
            return schools[schools.length - 1 - random.nextInt(4)];
        } else {
            return schools[random.nextInt(schools.length - 4)];
        }
    }
    
    /**
     * 获取随机院系
     */
    private String getRandomDepartment() {
        String[] departments = {"法学院", "计算机学院", "公共管理学院", "经济学院", "外国语学院", "社会学院", "心理学院", "体育学院", 
                             "数学院", "物理学院", "信息管理学院", "人工智能学院", "电子信息学院", "机械工程学院", "自动化学院", 
                             "刑事侦查学院", "公安管理学院", "治安学院", "警务指挥与战术学院", "网络安全学院", "交通管理学院"};
        
        Random random = new Random();
        if (random.nextInt(100) < 20) {
            // 返回警务相关院系的概率
            return departments[departments.length - 1 - random.nextInt(6)];
        } else {
            return departments[random.nextInt(departments.length - 6)];
        }
    }
    
    /**
     * 根据院系获取随机专业
     */
    private String getRandomMajor(String department) {
        HashMap<String, String[]> departmentMajors = new HashMap<>();
        departmentMajors.put("法学院", new String[]{"法学", "知识产权法", "国际法", "刑事法学", "民商法学"});
        departmentMajors.put("计算机学院", new String[]{"计算机科学与技术", "软件工程", "网络工程", "信息安全", "人工智能"});
        departmentMajors.put("公共管理学院", new String[]{"行政管理", "公共事业管理", "政治学与行政学", "社会保障", "人力资源管理"});
        departmentMajors.put("经济学院", new String[]{"经济学", "金融学", "国际经济与贸易", "财政学", "统计学"});
        departmentMajors.put("外国语学院", new String[]{"英语", "日语", "法语", "德语", "翻译学"});
        departmentMajors.put("社会学院", new String[]{"社会学", "社会工作", "人类学", "民俗学", "人口学"});
        departmentMajors.put("心理学院", new String[]{"心理学", "应用心理学", "犯罪心理学", "心理咨询", "教育心理学"});
        departmentMajors.put("体育学院", new String[]{"体育教育", "运动训练", "武术与民族传统体育", "体育管理", "警务体能"});
        departmentMajors.put("刑事侦查学院", new String[]{"刑事侦查学", "刑事科学技术", "侦查技术", "法医学", "痕迹检验学"});
        departmentMajors.put("公安管理学院", new String[]{"公安管理学", "警务指挥与战术", "社区警务", "公安情报学", "警察体能训练学"});
        departmentMajors.put("治安学院", new String[]{"治安学", "户政管理", "出入境管理", "边防管理", "禁毒学"});
        departmentMajors.put("警务指挥与战术学院", new String[]{"警务指挥与战术", "应急警务技术", "警卫学", "反恐怖学", "特种警务"});
        departmentMajors.put("网络安全学院", new String[]{"网络安全", "信息安全", "计算机犯罪侦查", "电子数据取证", "网络犯罪防控"});
        departmentMajors.put("交通管理学院", new String[]{"交通管理工程", "道路交通管理", "交通事故勘查", "车辆管理", "智能交通"});
        
        if (!departmentMajors.containsKey(department)) {
            String[] defaultMajors = {"行政管理", "治安学", "经济学", "法学", "计算机科学与技术", "英语", "金融学", "社会学"};
            return defaultMajors[new Random().nextInt(defaultMajors.length)];
        }
        
        String[] majors = departmentMajors.get(department);
        return majors[new Random().nextInt(majors.length)];
    }
    
    /**
     * 获取随机资格审查结果
     */
    private String getRandomQualificationResult() {
        String[] results = {"通过", "审核中", "未通过", "待补充材料"};
        int randomIndex = new Random().nextInt(100);
        if (randomIndex < 75) return results[0]; // "通过"的概率较高
        if (randomIndex < 85) return results[1]; // "审核中"的概率适中
        if (randomIndex < 95) return results[2]; // "未通过"的概率较低
        return results[3]; // "待补充材料"的概率最低
    }

    /**
     * 读取 count.txt 文件内容并返回给前端，并且每调用一次该接口count.txt中的数值增加1写回count.txt
     */
    @GetMapping("/getTitle")
    public AjaxResult getTitle() {
        String countPath = RuoYiConfig.getProfile()+ "\\count.txt";
        String titlePath = RuoYiConfig.getProfile()+ "\\title.txt";

        try {
            String countcontent = new String(Files.readAllBytes(Paths.get(countPath)));
            String titlecontent = new String(Files.readAllBytes(Paths.get(titlePath)));

            int count = Integer.parseInt(countcontent.trim());

            Map<String, Object> result = new HashMap<>();
            result.put("content", titlecontent);
            String formattedCounter = String.format("%04d", count);
            result.put("count", "LN"+formattedCounter);

            count = count + 1;
            // 确保写回文件时使用正确的路径
            Files.write(Paths.get(countPath), String.valueOf(count).getBytes());
            return success(result);
        } catch (IOException e) {
            return error("读取文件失败: " + e.getMessage());
        }
    }

    /**
     * 获取警校考生资格审查信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:qualification:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(qualificationStudentService.selectQualificationStudentById(id));
    }

    /**
     * 新增警校考生资格审查信息
     */
    @PreAuthorize("@ss.hasPermi('system:qualification:add')")
    @Log(title = "警校考生资格审查信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody QualificationStudent qualificationStudent)
    {
        return toAjax(qualificationStudentService.insertQualificationStudent(qualificationStudent));
    }

    /**
     * 修改警校考生资格审查信息
     */
    @PreAuthorize("@ss.hasPermi('system:qualification:edit')")
    @Log(title = "警校考生资格审查信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QualificationStudent qualificationStudent)
    {
        return toAjax(qualificationStudentService.updateQualificationStudent(qualificationStudent));
    }

    /**
     * 批量修改警校考生资格审查结果
     */
    @PreAuthorize("@ss.hasPermi('system:qualification:edit')")
    @Log(title = "警校考生资格审查信息", businessType = BusinessType.UPDATE)
    @PutMapping("/batchPass")
    public AjaxResult batchPass(@RequestBody List<QualificationStudent> qualificationStudentList)
    {
        return toAjax(qualificationStudentService.batchUpdateQualificationReview(qualificationStudentList));
    }

    /**
     * 删除警校考生资格审查信息
     */
    @PreAuthorize("@ss.hasPermi('system:qualification:remove')")
    @Log(title = "警校考生资格审查信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(qualificationStudentService.deleteQualificationStudentByIds(ids));
    }
}
